<?php

namespace App\Tasks;

use App\Models\Account;
use App\Models\AccountMapping;
use App\Models\Mall;
use App\Models\MallDateFinance;
use App\Models\ProjectMall;

class MeiTuanMallTask
{
    protected AccountMapping $account;

    protected Mall $mall;

    public function __construct(AccountMapping $mapping)
    {
        $this->mall = $mapping->mall;
        $this->account = $mapping;
    }

    public function maxDate($diffDay = 8){
        $maxDate = MallDateFinance::query()
            ->where("merchant_no",$this->mall->merchant_no)
            ->max("date");
        if(empty($maxDate)){
            if(!empty($this->account->mall->sub_date)){
                $maxDate = $this->account->mall->sub_date;
            }else{
                $maxDate = "2025-01-01";
            }
            $startDate = $maxDate;
        }else{
            $startDate = date("Y-m-d",strtotime($maxDate) - $diffDay * 86400);
        }
        if(!empty($this->account->mall->sub_date) and strtotime($startDate) <= strtotime($this->account->mall->sub_date)){
            $startDate = $this->account->mall->sub_date;
        }
        return $startDate;
    }

    protected function updateIncom()
    {
        $settleMoney = MallDateFinance::query()
            ->where("merchant_no",$this->mall->merchant_no)
            ->sum("settle_money");
        $malls = ProjectMall::query()->where("merchant_no",$this->mall->merchant_no)->get();
        foreach ($malls as $mall){
            if($settleMoney < $mall->money){
                $mall->incom_status = 0;
            }elseif ($settleMoney >= $mall->money * (1 + $mall->income_rate / 100)){
                $mall->incom_status = 2;
            }else{
                $mall->incom_status = 1;
            }
            $mall->save();
        }
    }
}
